<template>
  <ElementDialog ref="dialog" :visible="visible" embed :title="title" :width="width" :height="height" v-on="$listeners">
    <template #default>
      <slot name="search-form" :search-model="model" :search="search"></slot>
      <PageableTable
        ref="pageableTable"
        highlight-current-row
        hide-on-single-page
        click-row-select
        style="height: 60vh"
        :model="model"
        :columns="columns"
        :api="api"
        payload-style="body"
        row-class-name="pointer"
        :multiple="multiple"
        :descs="descs"
        @selection-change="selectionChange"
        @current-change="currentChange">
        <slot></slot>
      </PageableTable>
    </template>
    <template #footer>
      <ElButton size="mini" type="primary" @click="confirm">确 定</ElButton>
      <ElButton size="mini" @click="close">关 闭</ElButton>
    </template>
  </ElementDialog>
</template>

<script>
  import { filterTableColumnProperties } from '@/util'

  export default {
    name: 'DataTablePicker',
    props: {
      visible: Boolean,
      api: Function,
      columns: Array,
      title: String,
      width: {
        type: String,
        default: '60vw'
      },
      height: {
        type: String,
        default: null
      },
      model: {
        type: Object,
        default: () => {}
      },
      multiple: {
        type: Boolean,
        default: true
      },
      descs: String
    },
    data() {
      return {
        selectedRows: [],
        currentRow: null
      }
    },
    methods: {
      filterTableColumnProperties,
      selectionChange(selectedRows) {
        this.selectedRows = selectedRows
      },
      currentChange(currentRow) {
        this.currentRow = currentRow
      },
      confirm() {
        if (this.multiple) {
          if (this.selectedRows?.length) {
            this.$emit('confirm', this.selectedRows)
            this.close()
          } else {
            this.$message.warning('请选择')
          }
        } else {
          if (this.currentRow) {
            this.$emit('confirm', this.currentRow)
            this.close()
          } else {
            this.$message.warning('请选择')
          }
        }
      },
      async search() {
        await this.$refs.pageableTable?.reload()
      },
      close() {
        this.$refs.dialog.hide()
      }
    }
  }
</script>
